<template>
  <div class="category-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h2 class="page-title">分类管理</h2>
      <div class="page-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加分类</el-button>
        <el-input 
          placeholder="搜索分类名称" 
          v-model="searchForm.categoryName" 
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 分类列表表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table 
        :data="categoryList" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        class="category-table"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="categoryId" label="分类ID" width="200" align="center"></el-table-column>
        <el-table-column prop="categoryName" label="分类名称" width="180" align="center"></el-table-column>
        <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column prop="createUser" label="创建人" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        background
      >
      </el-pagination>
    </div>

    <!-- 分类编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :before-close="handleDialogClose">
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px" class="category-form">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="categoryForm.description" :rows="4" placeholder="请输入分类描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategoryForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'CategoryManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        categoryName: ''
      },
      // 分页信息
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 分类列表
      categoryList: [],
      loading: false,
      // 分类编辑对话框
      dialogVisible: false,
      dialogTitle: '新增分类',
      categoryForm: this.initCategoryForm(),
      rules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchCategoryList();
  },
  methods: {
    // 初始化分类表单
    initCategoryForm() {
      return {
        categoryId: '',
        categoryName: '',
        description: '',
        createUser: '',
        createTime: '',
        token: localStorage.getItem('token')

      };
    },
    // 获取分类列表
    async fetchCategoryList() {
      this.loading = true;
      try {
        const params = {
          pageNum: this.page.currentPage,
          pageSize: this.page.pageSize,
          categoryName: this.searchForm.categoryName
        };
        const res = await service.get('/api/study/category/getCategoryList', { params });
        
        if (res.code === 200) {
          this.categoryList = res.data.list || [];
          this.page.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取分类列表失败');
        }
        this.loading = false;
      } catch (error) {
        console.error('获取分类列表失败', error);
        this.$message.error('获取分类列表失败，请稍后重试');
        this.loading = false;
      }
    },
    // 处理查询
    handleSearch() {
      this.page.currentPage = 1;
      this.fetchCategoryList();
    },
    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        categoryName: ''
      };
      this.handleSearch();
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.fetchCategoryList();
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.fetchCategoryList();
    },
    // 添加分类
    handleAdd() {
      this.dialogTitle = '新增分类';
      this.categoryForm = this.initCategoryForm();
      this.dialogVisible = true;
    },
    // 编辑分类
    handleEdit(row) {
      this.dialogTitle = '编辑分类';
      this.categoryForm = { ...row };
      this.categoryForm.token = localStorage.getItem('token');
      this.dialogVisible = true;
    },
    // 删除分类
    handleDelete(row) {
      this.$confirm(`确认删除分类"${row.categoryName}"吗？这将同时影响关联的文章。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await service.delete(`/api/study/category/deleteCategory/${row.categoryId}`);
          
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchCategoryList();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除分类失败', error);
          this.$message.error('删除分类失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 提交分类表单
    submitCategoryForm() {
      this.$refs.categoryForm.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.categoryForm.categoryId) {
              res = await service.put('/api/study/category/updateCategory', this.categoryForm);
            } else {
              res = await service.post('/api/study/category/addCategory', this.categoryForm);
            }
            
            if (res.code === 200) {
              this.$message.success('保存成功');
              this.dialogVisible = false;
              this.fetchCategoryList();
            } else {
              this.$message.error(res.message || '保存失败');
            }
          } catch (error) {
            console.error('保存分类失败', error);
            this.$message.error('保存分类失败，请稍后重试');
          }
        } else {
          return false;
        }
      });
    },
    // 关闭分类编辑对话框
    handleDialogClose(done) {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.category-form .el-form-item {
  margin-bottom: 22px;
}

/* 表格样式优化 */
.category-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.category-table tr:hover {
  background-color: #f5f7fa;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 10px;
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
    margin-top: 10px;
  }
}
</style> 